import axios from 'axios';
// 引入路由
import router from '@/router';
import { MessageBox } from 'element-ui'



// http request 拦截器
// axios.interceptors.request.use(
//     config => {
//         if (store.state.token) {
//             // 判断是否存在 token, 如果存在的话, 则每个 http header 都加上 token
//             config.headers.Authorization = `token ${store.state.token}`;
//         }
//         return config;
//     },
//     err => {
//         return Promise.reject(err);
//     });


// 添加响应拦截器
axios.interceptors.response.use(
    function (response) {
        // 对响应数据进行操作
        return response;
    },
    function (error) {
        if (error.response.data.code == 999) {
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                type: 'warning'
            }
            ).then(() => {
                localStorage.removeItem('userInfo')
                localStorage.removeItem('token')
                // router.push({ path: '/login' })
                window.location.reload();
            }).catch(() => {
                MessageBox.close
            });
        }
        // 对响应错误进行操作
        return Promise.reject(error);
    }
);


//自己封装
const request = (method, url, params) => {
    return axios({
        method: method,
        url: url,
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
        },
        data: params,
        traditional: true
    }).then(res => res.data);
};
const requestToken = (method, url, params) => {
    return axios({
        method: method,
        url: url,
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            token: localStorage.getItem('token')
        },
        data: params,
        traditional: true
    }).then(res => res.data);
};
const download = (url, params, filename) => {
    axios({
        method: 'GET',
        url: url,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            token: localStorage.getItem('token')
        },
        params: params,
        responseType: 'blob',
    }).then((res) => {
        const blob = new Blob([res.data], { type: 'application/zip' }); // new一个二进制对象
        const url = window.URL.createObjectURL(blob); // 转化为url
        const link = document.createElement('a'); // 创建个a标签
        link.href = url;
        link.download = filename; // 重命名
        link.click();
        URL.revokeObjectURL(url); // 释放内存
    });
}


export {
    request,
    requestToken,
    download
}